/* 
 * File:   worker.cpp
 * Author: zhouxich
 * Description: 工作者线程，用于从任务队列取出任务并与存储系统打交道，处理客户相关数据
 */
#include "server.h"

void*
worker(void* arg){

	pthread_detach(pthread_self());

    	struct stat sbuf;

	for(;;){
		/*从任务队列取得任务*/
		task mytask = task_get(&handler);
	    			
		if (stat(mytask.filename, &sbuf) < 0) {
			clienterror(mytask.output, mytask.fd, mytask.filename, 
						"404", "Not found", "Tiny couldn't find this file");
			continue;
		}

		if (mytask.is_static) { 
			if (!(S_ISREG(sbuf.st_mode)) || !(S_IRUSR & sbuf.st_mode)) {
				clienterror(mytask.output, mytask.fd, mytask.filename, "403", "Forbidden", "Tiny couldn't read the file");
				continue;
			}
			serve_static(mytask.output, mytask.fd, mytask.filename, sbuf.st_size);
		}
		else { 
			if (!(S_ISREG(sbuf.st_mode)) || !(S_IXUSR & sbuf.st_mode)) {
				clienterror(mytask.output, mytask.fd, mytask.filename, "403", "Forbidden", "Tiny couldn't run the CGI program");
				continue;
			}
			serve_dynamic(mytask.fd, mytask.filename, mytask.cgiargs, 
						mytask.req_method, mytask.input, mytask.content_length);
		 }
	}
	return NULL;
}


void
worker_make(){
	pthread_t tid;
	pthread_create(&tid, NULL, &worker, NULL);
	return;
}
